package ext.mango.ab.so;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ext.mango.base.POBase;
import ext.mango.functions.Func;
import ext.mango.ab.eo.EOABMessage;

import mango.functions.FuncString;
import mango.orm.DBSession;
import mango.orm.DBSessionFactory;
import mango.service.Service;

@Service
public class SOABMessage {
    private Log log = LogFactory.getLog(SOABMessage.class);
    private static final String yatouNo = "13739715615";
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");

    public EOABMessage toMessage(String msg) throws Exception {
        EOABMessage entity = new EOABMessage();
        String phoneRegex = "\\d{5,}";
        Pattern phonePat = Pattern.compile(phoneRegex);
        Matcher phoneMac = phonePat.matcher(msg);

        boolean isMessage = true;
        if (msg.indexOf("sms") >= 0) {
            entity.setType("sms");
            if (msg.indexOf("deliver") >= 0) {
                if (phoneMac.find()) {
                    entity.setSender(phoneMac.group());
                }
                entity.setReciver(yatouNo);
            }
            else if (msg.indexOf("submit") >= 0) {
                entity.setSender(yatouNo);
                if (phoneMac.find()) {
                    entity.setReciver(phoneMac.group());
                }
            }
        }
        else if (msg.indexOf("mms") >= 0) {
            entity.setType("mms");
            int phoneNum = 0;
            String[] phoneNo = new String[2];
            while (phoneMac.find()) {
                phoneNo[phoneNum] = phoneMac.group();
                phoneNum++;
            }
            if (phoneNum == 2) {
                entity.setSender(phoneNo[0]);
                entity.setReciver(phoneNo[1]);
            }
            else if (phoneNum == 1) {
                entity.setSender(yatouNo);
                entity.setReciver(phoneNo[0]);
            }
        }
        else {
            isMessage = false;
        }

        if (!isMessage) {
            return null;
        }

        String dateRegex = "\\D{1}\\d{4}\\D{1}.*:\\d{2}";
        Pattern datePat = Pattern.compile(dateRegex);
        Matcher dateMac = datePat.matcher(msg);
        if (dateMac.find()) {
            String sendDate = dateMac.group().substring(1);
            entity.setSendDate(sdf.parse(sendDate));
            int start = msg.indexOf(sendDate) + sendDate.length() + 6;
            String message = msg.substring(start, msg.length() - 1).trim();
            if (message.endsWith("\"")) {
                message = message.substring(0, message.length() - 1);
            }
            entity.setMessage(message);
        }
        return entity;
    }

    public boolean importMsg(POBase action) {
        try {
            this.log.debug("---数据导入 开始---");
            InputStream stream = action.getRequestUploadStream("file");
            String batchNo = (String) action.getExtra("BATCHNO");
            String usrId = action.getCurrentUser().getId();

            long start = System.currentTimeMillis();

            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "gb2312"));
            try {
                String line = null;
                List<EOABMessage> msgs = new ArrayList<EOABMessage>();
                while ((line = reader.readLine()) != null) {
                    if (FuncString.isBlank(line)) {
                        continue;
                    }
                    try {
                        EOABMessage entity = this.toMessage(line);
                        if (entity != null) {
                            entity.setId(UUID.randomUUID().toString()).setBatchNo(batchNo)
                                    .setOperator(usrId).setMakeDate(new Date()).setAvliable("1");
                            msgs.add(entity);
                        }
                    }
                    catch (Exception e) {
                        log.warn("消息转换失败：" + line);
                        continue;
                    }
                }
                DBSession session = DBSessionFactory.getCurrentSession();
                session.save(msgs);
                session.commit();
                this.log.debug("---数据导入 结束，用时： " + Func.getSpendTime(start));
                return true;
            }
            finally {
                reader.close();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
